//
//  CTEditeImageView.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/5/15.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTEditeImageView.h"
#import "CTDebugManager.h"
#import "CTHeader.h"
#import "CTAppLanguage.h"

#import "CTStickerView.h"

#import "CTEmojiCollectionView.h"
#import "CTEmojiDetailsCollection.h"
#import "CTRequestUtil.h"
#import "CTPublishItems.h"
#import "CTDeviceFunction.h"
#import "CTTextManager.h"


@interface CTEditeImageView ()<CTStickerViewDelegate,CTEmojiCollectionViewDelegate,CTEmojiDetailsCollectionDelegate>
{
    UIView * topView;
    
    UIImageView * editImageView;
    
    UITextView *textView;
    
    UITapGestureRecognizer *singleTap;
    CGFloat currentFontSize;
    
    CTEmojiCollectionView *emojiCollectionView;
    CTEmojiDetailsCollection * emojiDetailsCollection;
//    NSMutableArray * topicArray;
//    NSMutableArray * group_id_ary;
//    NSMutableArray * scheme_id_ary;
    
}
@property (nonatomic, strong) CTStickerView *textView;
@end

@implementation CTEditeImageView
@synthesize delegate;


- (void)dealloc
{
//    topicArray = nil;
//    group_id_ary = nil;
//    scheme_id_ary = nil;
    topView = nil;
    delegate = nil;
    [emojiCollectionView removeFromSuperview];
    emojiCollectionView = nil;
    [emojiDetailsCollection removeFromSuperview];
    emojiDetailsCollection = nil;
    textView = nil;
    [singleTap removeTarget:editImageView action:@selector(onClickImage)];
    singleTap = nil;
    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTEditeImageView Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
//        topicArray = [NSMutableArray array];
//        group_id_ary = [NSMutableArray array];
//        scheme_id_ary = [NSMutableArray array];
        currentFontSize = 13.0;
        self.frame = CGRectMake(0, 0, CT_HEADER_SCREEN_WIDTH, CT_HEADER_SCREEN_HEIGHT);
        self.backgroundColor = [UIColor whiteColor];
        
        
        [self creatSubviews];
        
        emojiCollectionView = [[CTEmojiCollectionView alloc]initWithFrame:CGRectMake(0,CT_HEADER_SCREEN_HEIGHT-75, CT_HEADER_SCREEN_WIDTH, 75)];
        emojiCollectionView.delegate = self;
        [self addSubview:emojiCollectionView];
        
        emojiDetailsCollection = [[CTEmojiDetailsCollection alloc]initWithFrame:CGRectMake(0, CT_HEADER_SCREEN_HEIGHT-170, CT_HEADER_SCREEN_WIDTH, 95)];
        emojiDetailsCollection.delegate = self;
        [self addSubview:emojiDetailsCollection];
        
        
    }
    return self;
}


#pragma mark - creat subViews -
-(void)creatSubviews
{
    
    topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CT_HEADER_SCREEN_WIDTH, 64)];
    topView.backgroundColor = CT_HEADER_WHITE_COLOR;
    [self addSubview:topView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, CT_HEADER_SCREEN_WIDTH, 44)];
    titleLabel.text = [CTAppLanguage localizedStringForKey:@"editView_topView_title" withValue:nil withTable:@"Language"];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = CT_HEADER_GREEN_COLOR;
    titleLabel.font = [UIFont fontWithName:nil size:19];
    [topView addSubview:titleLabel];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 44, 44);
    [backButton addTarget:self action:@selector(backBtn:) forControlEvents:UIControlEventTouchUpInside];
    [backButton setImage:[UIImage imageNamed:CT_HEADER_BACK_IMAGE] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:CT_HEADER_BACK_IMAGE_CLICK] forState:UIControlStateHighlighted];
    [topView addSubview:backButton];
    
    UIButton * confirmBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(CT_HEADER_SCREEN_WIDTH-60, 20, 55, 44);
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [confirmBtn addTarget:self action:@selector(nextStepBtn:) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn setTitleColor:CT_HEADER_GREEN_COLOR forState:UIControlStateNormal];
    [confirmBtn setTitle:[CTAppLanguage localizedStringForKey:@"editView_topView_next" withValue:nil withTable:@"Language"] forState:UIControlStateNormal];
    [topView addSubview:confirmBtn];
    
    UILabel * topBottomLine = [[UILabel alloc]initWithFrame:CGRectMake(0, topView.frame.size.height-0.5, CT_HEADER_SCREEN_WIDTH, 0.5)];
    topBottomLine.backgroundColor = CT_HEADER_DEEPLINE_COLOR;
    [topView addSubview:topBottomLine];
    
    editImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, CT_HEADER_SCREEN_WIDTH, CT_HEADER_SCREEN_WIDTH)];
    editImageView.backgroundColor = [UIColor blackColor];
    editImageView.userInteractionEnabled = YES;
    editImageView.layer.masksToBounds = YES;
    [self addSubview:editImageView];
    
    singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickImage:)];
    [editImageView addGestureRecognizer:singleTap];
    
    
    
//    UIPanGestureRecognizer *panGes = [[UIPanGestureRecognizer alloc] initWithTarget:self
//                                                                             action:@selector(panAction:)];
//    [editImageView addGestureRecognizer:panGes];
    
    
    
    
    //////////////////////////////////////////////////////////////////////////////////////
    CGRect gripFrame1 = CGRectMake(50, 50, 140, 140);
    
//    CTStickerView *userResizableView1 = [[CTStickerView alloc]initWithFrame:gripFrame1 withType:CTStickerViewTypePic];
//    userResizableView1.image = [UIImage imageNamed:@"peitu_head"];
//    userResizableView1.preventsPositionOutsideSuperview = NO;
//    [userResizableView1 showEditingHandles];
//    [editImageView addSubview:userResizableView1];
////    [self setTextView:userResizableView1];
//    
////    [userResizableView1 hideEditingHandles];
//    CGRect gripFrame2 = CGRectMake(50, 200, 180, 180);
//    CTStickerView *userResizableView2 = [[CTStickerView alloc]initWithFrame:gripFrame2 withType:CTStickerViewTypeBubble];
//    userResizableView2.textStr = @"双击编辑";
//    userResizableView2.image = [UIImage imageNamed:@"peitu_head"];
//    userResizableView2.preventsPositionOutsideSuperview = NO;
//    [userResizableView2 showEditingHandles];
//    [editImageView addSubview:userResizableView2];
//    [self setTextView:userResizableView2];
}
- (void)panAction:(UIPanGestureRecognizer *)sender
{
    CGPoint translation = [sender translationInView:editImageView];
    
    CGPoint viewCenter = self.textView.center;
    
    viewCenter.x = viewCenter.x + translation.x;
    viewCenter.y = viewCenter.y + translation.y;
    
//    if (viewCenter.x - self.textView.frame.size.width  / 2. < 0. ||
//        viewCenter.x + self.textView.frame.size.width  / 2. > sender.view.frame.size.width)
//    {
//        viewCenter.x = self.textView.center.x;
//    }
//    
//    if (viewCenter.y - self.textView.frame.size.height / 2. < 0. ||
//        viewCenter.y + self.textView.frame.size.height / 2. > sender.view.frame.size.height)
//    {
//        viewCenter.y = self.textView.center.y;
//    }
    
    [self.textView setCenter:viewCenter];
    [sender setTranslation:CGPointZero inView:editImageView];
}


#pragma mark - action & delegate -

-(void)backBtn:(id)sender
{
    if ([self.delegate respondsToSelector:@selector(backAction:)]) {
        [self.delegate backAction:self];
    }
}

-(void)nextStepBtn:(id)sender
{
    UIImageView * superImageView = editImageView;
    NSArray * subviewsArr = [superImageView subviews];

    for (int i = 0; i<subviewsArr.count; i++) {
        id subView = [subviewsArr objectAtIndex:i];
        if ([subView isKindOfClass:[CTStickerView class]]) {
            
            CTStickerView * stickerView = (CTStickerView *)subView;
            
            [stickerView hideEditingHandles];
        }
    }
    
    [textView resignFirstResponder];
    
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    for (NSString  *str in topicArray)
//    {
//        [dict setObject:str forKey:str];
//    }
//    topicArray = (NSMutableArray*)[dict allKeys];
//    dict = nil;
//    
//    NSMutableDictionary *dicGroup = [NSMutableDictionary dictionary];
//    for (NSString * str in group_id_ary)
//    {
//        [dicGroup setObject:str forKey:str];
//    }
//    group_id_ary = (NSMutableArray *)[dicGroup allKeys];
//    dicGroup = nil;
//    
//    NSMutableDictionary *dicScheme = [NSMutableDictionary dictionary];
//    for (NSString * str in scheme_id_ary)
//    {
//        [dicScheme setObject:str forKey:str];
//    }
//    scheme_id_ary = (NSMutableArray *)[dicScheme allKeys];
//    dicScheme = nil;
    
    
    
    UIImage *img = [CTDeviceFunction imageFromView:editImageView atFrame:editImageView.bounds];
    
    UIImageView *waterImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, CT_HEADER_SCREEN_WIDTH-23-10, 68, 23)];
    waterImageView.image = [UIImage imageNamed:@"picopico"];
    [editImageView addSubview:waterImageView];
    
    UIImage *waterImg = [CTDeviceFunction imageFromView:editImageView atFrame:editImageView.bounds];
    waterImageView.hidden = YES;
    if ([self.delegate respondsToSelector:@selector(nextStepAction:withImage:withTopAry:withGroupAry:withSchemeAry:withWaterImage:)])
    {
        [self.delegate nextStepAction:self withImage:img withTopAry:nil withGroupAry:nil withSchemeAry:nil withWaterImage:waterImg];
    }
}


#pragma mark - gesture -

-(void)onClickImage:(id)sender
{
    UITapGestureRecognizer * gesture = (UITapGestureRecognizer *)sender;
    UIImageView * superImageView = (UIImageView *)gesture.view;
    
    NSArray * subviewsArr = [superImageView subviews];
    
    
    for (int i = 0; i<subviewsArr.count; i++) {
        id subView = [subviewsArr objectAtIndex:i];
        if ([subView isKindOfClass:[CTStickerView class]]) {
            
            CTStickerView * stickerView = (CTStickerView *)subView;
            [stickerView hideEditingHandles];
        }
    }
    
    [textView resignFirstResponder];
}

#pragma mark - sticker delegate -

-(void)stickerViewIsEditing:(CTStickerView *)sticker withWidth:(CGFloat)width withHeight:(CGFloat)height withScales:(CGFloat)scale
{
    currentFontSize += width/2000.0;
   // [textView setFont:[UIFont systemFontOfSize:currentFontSize]];
}

#pragma mark - CTEmojiCollectionViewDelegate -
- (void)selectedEmojiSubjects:(CTEmojiCollectionView *)view withItems:(NSArray *)itemArray withItem:(CTEditeEmojiListItem *)item
{

    emojiDetailsCollection.itemArray = itemArray;
    if ([self.delegate respondsToSelector:@selector(selectedEmojiSubjects:withItem:)])
    {
        [self.delegate selectedEmojiSubjects:self withItem:item];
    }
}

- (void)selectedEmoji:(CTEmojiCollectionView *)view withItems:(NSArray *)itemBubbleAry withIndexPath:(int)emojiIndexPath
{
    emojiDetailsCollection.itemArray = itemBubbleAry;
}

//字符串转颜色
- (UIColor *) stringTOColor:(NSString *)str
{
    if (!str || [str isEqualToString:@""]) {
        return nil;
    }
    unsigned red,green,blue;
    NSRange range;
    range.length = 2;
    range.location = 1;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&red];
    range.location = 3;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&green];
    range.location = 5;
    [[NSScanner scannerWithString:[str substringWithRange:range]] scanHexInt:&blue];
    UIColor *color= [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:1];
    return color;
}


#pragma mark = CTEmojiDetailsCollectionDelegate -
- (void)selectedEmojiDetailsCollection:(CTEmojiDetailsCollection *) view withItem:(CTEditeBubbleListItem *) item
{
    CGRect gripFrame2 = CGRectMake([item.x floatValue]/2.0, [item.y floatValue]/2.0, [item.w floatValue]/2.0, [item.h floatValue]/2.0);
//    CTStickerView *userResizableView2 = [[CTStickerView alloc]initWithFrame:gripFrame2 withType:CTStickerViewTypeBubble ];
    CTStickerView *userResizableView2 = [[CTStickerView alloc]initWithFrame:CGRectMake(50, 50, 150, 150) withType:CTStickerViewTypeBubble withTextViewFrame:gripFrame2];
    userResizableView2.textStr = @"双击编辑";
//    userResizableView2.rect = gripFrame2;
    userResizableView2.bubbleTextColor = [self stringTOColor:item.text_color];
    
    if ([[CTTextManager shareInstance] isBlankString:item.url] == NO) {
        [CTRequestUtil requestImgWithUrl:item.url withCompletionSuccessHandler:^(UIImage *img) {
            userResizableView2.image = img;
            //        NSLog(@"img-w  %f    h = %f",img.size.width,img.size.height);
            //        NSLog(@"w = %@  h = %@  x = %@   Y = %@",item.w,item.h,item.x,item.y);
        } withFailedHandler:^(NSError *error) {
            
        }];
    }else{
        userResizableView2.image = item.image;
    }
    
    userResizableView2.preventsPositionOutsideSuperview = NO;
    [userResizableView2 showEditingHandles];
    [editImageView addSubview:userResizableView2];
    [self setTextView:userResizableView2];

//        CGRect gripFrame1 = CGRectMake(50, 50, 140, 140);
//        CTStickerView *userResizableView1 = [[CTStickerView alloc]initWithFrame:gripFrame1 withType:CTStickerViewTypePic];
//        [CTRequestUtil requestImgWithUrl:item.url withCompletionSuccessHandler:^(UIImage *img) {
//            userResizableView1.image = img;
//        } withFailedHandler:^(NSError *error) {
//            
//        }];
//        userResizableView1.preventsPositionOutsideSuperview = NO;
//        [userResizableView1 showEditingHandles];
//        [editImageView addSubview:userResizableView1];


}

- (void)emojiDetailsCollection:(CTEmojiDetailsCollection *)view withItem:(CTEditeEmojiListDetailsItem *)item
{
    CGRect gripFrame1 = CGRectMake(50, 50, 140, 140);
    CTStickerView *userResizableView1 = [[CTStickerView alloc]initWithFrame:gripFrame1 withType:CTStickerViewTypePic withTextViewFrame:gripFrame1];
    [CTRequestUtil requestImgWithUrl:item.url withCompletionSuccessHandler:^(UIImage *img) {
        userResizableView1.image = img;
    } withFailedHandler:^(NSError *error) {

    }];
    

    
    userResizableView1.stickerItem = item;
    userResizableView1.delegate = self;
    userResizableView1.preventsPositionOutsideSuperview = NO;
    [userResizableView1 showEditingHandles];
    [editImageView addSubview:userResizableView1];
    if ([self.delegate respondsToSelector:@selector(selectedScheme:withItem:)])
    {
        [self.delegate selectedScheme:self withItem:item];
    }
}
#pragma mark - StickerViewDelegate -
- (void)stickerViewDidClose:(CTStickerView *)sticker withItem:(CTEditeEmojiListDetailsItem *)item
{
    if ([self.delegate respondsToSelector:@selector(selectedCloseBtn:withItem:)])
    {
        [self.delegate selectedCloseBtn:self withItem:item];
    }
}
#pragma mark - setter -

-(void)setEditImg:(UIImage *)editImg
{
    editImageView.image = editImg;
}

- (void)setEditeArray:(NSArray *)editArray
{
    emojiCollectionView.itemArray = editArray;
}

-(void)setBubblesArray:(NSArray *)bubblesArr
{
    emojiCollectionView.bobbleItemArray = bubblesArr;
}

@end
